package hust.rpc.server;

import hust.rpc.common.HelloService;
import hust.rpc.procotol.JsonRpcRequest;
import hust.rpc.procotol.JsonRpcResponse;
import hust.rpc.server.impl.HelloServiceImpl;
import hust.rpc.util.JsonUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 服务端业务逻辑处理 handler
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 接收到客户端消息，并解析出方法并调用实际服务，最后返回结果给客户端
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        System.out.println("收到消息" + msg);

        JsonRpcRequest request = JsonUtil.readRequestFromString((String) msg);

        String method = request.getMethod();

        if (method.equals(HelloService.class.getName() + ".hello")){
            String[] split = request.getParams().split("#");
            String result = new HelloServiceImpl().hello(split[0]);

            JsonRpcResponse response = new JsonRpcResponse.Builder()
                    .withId(request.getId())
                    .withResult(result)
                    .build();

            ctx.writeAndFlush(JsonUtil.writeResponseAsString(response));
        }

    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
